package com.fund.datacopy.task.thread;

import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;

import com.aug3.sys.util.DateUtil;
import com.fund.datacopy.bean.Group;
import com.fund.datacopy.conf.Constants;
import com.fund.datacopy.env.EnvConfigure;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;

public class Allocater implements Runnable {
	private ExecutorService executor = Executors.newFixedThreadPool(Constants.poolSize);

	public Group g;

	public Allocater() {
	}

	public Allocater(Group g) {
		this.g = g;
	}

	public Group getG() {
		return this.g;
	}

	public void setG(Group g) {
		this.g = g;
	}

	public void work() throws Exception {
		if ((this.g == null) || (CollectionUtils.isEmpty(this.g.getTable()))) {
			System.err.println("-----配置不对----");
			return;
		}
		String src = this.g.getSrc();
		String dest = this.g.getDest();

		if (StringUtils.isBlank(src)) {
			src = Constants.MGT_DB_URL;
		}

		if (StringUtils.isBlank(dest)) {
			dest = Constants.DEV_DB_URL;
		}
		List<String> tables = this.g.getTable();
		List<String> colnums = this.g.getCollum();
		List<String> exts = this.g.getExt();
		List<String> styles = this.g.getStyle();
		for (int i = 0; i < tables.size(); i++) {
			String table = (String) tables.get(i);
			EnvConfigure conf = new EnvConfigure();
			conf.setUrl(src);
			conf.setDb(this.g.getDb());
			conf.setTable(table);

			EnvConfigure conf2 = new EnvConfigure();
			conf2.setUrl(dest);
			conf2.setDb(this.g.getDb());
			conf2.setTable(table);

			DBCollection conn = conf.getMongoConnection();

			DBCollection conn2 = conf2.getMongoConnection();

			BasicDBObject q = new BasicDBObject();
			String colnum = null;
			if (CollectionUtils.isNotEmpty(colnums)) {
				colnum = (String) colnums.get(i);
			}

			if (StringUtils.isNotBlank(colnum)) {
				if ((CollectionUtils.isNotEmpty(exts)) && (exts.size() > i)) {
					String ex = (String) exts.get(i);
					String[] vals = ex.split(Constants.COMMA);
					q.append(colnum, new BasicDBObject("$in", vals));
				} else if ((CollectionUtils.isNotEmpty(styles)) && (styles.size() > i)) {
					String style = (String) styles.get(i);
					q.append(colnum, DateUtil.formatDate(new Date(), style));
				} else {
					q.append(colnum, DateUtil.formatDate(new Date(), Constants.DEFAULT_DT_STYLE));
				}
			}

			this.executor.execute(new Worker(conn, conn2, q));
		}
		this.executor.shutdown();
	}

	public void run() {
		try {
			System.out.println("alloct resource .." + this.g.getName());
			work();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
